package spring.cloud.eureka.client;

import java.util.concurrent.ThreadLocalRandom;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.netflix.discovery.EurekaClient;

@RestController
public class GreetingControllerImpl implements GreetingController {
	@Autowired
    @Lazy
    private EurekaClient eurekaClient;

    @Value("${spring.application.name}")
    private String appName;
    
    
    //, blockHandlerClass = {ExceptionUtil.class}
    @Override
	    public String greeting() {
    	if (ThreadLocalRandom.current().nextInt(0, 100) > 55) {

			throw new RuntimeException("RuntimeException from greeting");

		}
        return String.format("Hello from '%s'!", eurekaClient.getApplication(appName).getName());
	    } 
//    
//    //, blockHandlerClass = {ExceptionUtil.class}
//    @Override
//    @SentinelResource(value = "flowQps", defaultFallback = "defaultFallback",
//    		blockHandler="blockHandler",
//    exceptionsToIgnore = {IllegalStateException.class})
//	    public String greeting() {
//    		
//	        return String.format("Hello from '%s'!", eurekaClient.getApplication(appName).getName());
//	    } 
    
//    public static String  handleStringException(BlockException ex) {

    public   String blockHandler(BlockException ex) {
    	 return String.format("Hello from '%s'!", "blockHandler");
    	
    }
    
    public String defaultFallback() {
    	return "Hello from defaultFallback";
    }

	@Override
    @SentinelResource(value = "flowQps", defaultFallback = "defaultFallback",
	blockHandler="handleStringException",  blockHandlerClass = {ExceptionUtil.class},
    exceptionsToIgnore = {IllegalStateException.class})
	public String another() {
		// TODO Auto-generated method stub
   	 return String.format("Hello from '%s'!", "another");

	}
    
}
